import { FindOneOptions, Repository, SelectQueryBuilder } from 'typeorm';
/**
 *  total ：总条数
    pageSize ：每页条数
    currentPage ：当前页
    totalPage ：总共有多少页
    isEnd ：是否还有下一页
    list ：查询出来的列表对象
 */
export class PaginationResult<T> {
  total: number;
  pageSize: number;
  currentPage: number;
  totalPage: number;
  isEnd: boolean;
  list: T[];
}

export class PaginationService<T> {
  constructor(private readonly repository: Repository<T>) {
    // console.log('repository:==>', this.repository);
  }

  // 普通分页查询
  async paginate(params: {
    page: number;
    pageSize: number;
    options?: FindOneOptions<T>;
  }): Promise<PaginationResult<T>> {
    const { page = 1, pageSize = 10, options = {} } = params || {};
    const [result, total] = await this.repository.findAndCount({
      take: pageSize,
      skip: pageSize * (page - 1),
      ...options,
    });

    const paginationResult = new PaginationResult<T>();
    paginationResult.list = result;
    paginationResult.total = total;
    paginationResult.pageSize = pageSize;
    paginationResult.currentPage = page;
    paginationResult.totalPage = Math.ceil(total / pageSize);
    paginationResult.isEnd = paginationResult.totalPage === page;

    return paginationResult;
  }

  // 查询构造器-进行分页查询
  async pageSearch(params: {
    page: number;
    pageSize: number;
    queryBuilder?: SelectQueryBuilder<T>;
  }) {
    const { page, pageSize, queryBuilder } = params;
    const skip = (page - 1) * pageSize;
    const take = pageSize;
    // 查询构造器
    let qb: SelectQueryBuilder<T>;
    qb = queryBuilder ? queryBuilder : this.repository.createQueryBuilder();

    // 根据查询构造器查询结果 
    const [list, total] = await qb.skip(skip).take(take).getManyAndCount();
    // console.log('查询构造器查询结果', [list, total]);

    // 构造分页查询结果
    const resp = new PaginationResult<T>();
    resp.list = list;
    resp.total = total;
    resp.pageSize = pageSize;
    resp.currentPage = page;
    resp.totalPage = Math.ceil(total / pageSize);
    resp.isEnd = [page, 0].includes(resp.totalPage);
    return resp;
  }
}
